package com.huawei.virest.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.huawei.virest.common.SystemInit;
import com.huawei.virest.common.domain.HttpResp;
import com.huawei.virest.common.util.HttpUtils;
import com.huawei.virest.domain.StructuredData;

@SuppressWarnings("serial")
@Controller
public class RestClientAction extends HttpServlet {
	protected final transient Log log = LogFactory.getLog(RestClientAction.class);

	public RestClientAction() {

	}

	@RequestMapping(method = RequestMethod.POST, value = "/restClient.html")
	public String restClient(HttpServletRequest request, ModelMap modelMap)
			throws Exception {
		String url = request.getParameter("url");
		String method = request.getParameter("method");
		String key = request.getParameter("key");
		String value = request.getParameter("value");
		String keyTwo = request.getParameter("keyTwo");
		String valueTwo = request.getParameter("valueTwo");
		// value = new String(value.getBytes("ISO8859-1"), "utf-8");
		String body = request.getParameter("body");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile attachment = multipartRequest.getFile("attachment");
		File file = null;
		if (null != attachment) {
			if (!attachment.isEmpty()) {
				file = mapMultipartFileToFile(attachment);
			}
		}

		Map<String, Object> requestData = new HashMap<String, Object>();
		requestData.put("URL", url);
		requestData.put("method", method);
		if (null != body) {
			requestData.put("body", body);
		}
		if (file != null) {
			requestData.put("file", file);
		}
		Map<String, String> headerValues = new HashMap<String, String>();
		headerValues.put(key, value);
		if (keyTwo.length() != 0 && valueTwo.length() != 0) {
			headerValues.put(keyTwo, valueTwo);
		}
		requestData.put("headers", headerValues);

		HttpResp resp = HttpUtils.getInstance().request(requestData);
		modelMap.put("response", resp.getResponse());
		modelMap.put("httpStatus", resp.getHttpStatus());
		modelMap.put("statusText", resp.getStatusText());
		request.setAttribute("response", resp.getResponse());
		request.setAttribute("url", url);
		request.setAttribute("body", body);
		request.setAttribute("key", key);

		value = value.replaceAll("\"", "&quot;");
		request.setAttribute("value", value);
		request.setAttribute("method", method);
		if (keyTwo.length() != 0 && valueTwo.length() != 0) {
			request.setAttribute("keyTwo", keyTwo);
			request.setAttribute("valueTwo", valueTwo);
		}

		return "restClient";
	}

	public File mapMultipartFileToFile(MultipartFile f) throws IOException {
		// 上传的临时文件
		File upFile = null;
		String path = SystemInit.getConfig().getAbsolutePath() + "uploadtemp\\";
		// Constants.getAbsolutePath() + "uploadtemp\\";
		DiskFileItemFactory dfif = new DiskFileItemFactory();

		// 设定使用内存超过5M时，将产生临时文件并存储于临时目录中。ONE_THOUSAND_AND_TWENTY_FOUR
		dfif.setSizeThreshold(5 * 1024 * 1024);
		dfif.setRepository(new File(path)); // 设定存储临时文件的目录。

		ServletFileUpload fileupload = new ServletFileUpload(dfif);

		// 设定最大允许上传5M的文件。
		fileupload.setSizeMax(5 * 1024 * 1024);

		String filename = UUID.randomUUID() + f.getOriginalFilename();// 保证临时文件不会有重名
		upFile = new File(path, filename);
		createFile(upFile);

		FileOutputStream fos = new FileOutputStream(upFile);
		fos.write(f.getBytes());
		fos.close();

		return upFile;

	}

	public static boolean createDirector(File dir) {
		return dir.mkdirs();
	}

	/**
	 * createFile
	 * 
	 * @param file
	 *            file
	 * @return boolean
	 * @throws IOException
	 *             IOException
	 */
	public static boolean createFile(File file) throws IOException {
		if (!file.exists()) {
			File parent = file.getParentFile();
			if (createDirector(parent)) {
				return file.createNewFile();
			}
			return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(method = RequestMethod.POST, value = "/openRequest.html")
	public String openRequest(HttpServletRequest request, ModelMap modelMap)
			throws Exception {
		String method = "";
		String value = "";
		String key = "";
		String keyTwo = null;
		String valueTwo = null;
		String body = "";
		String url = "";

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile rcqFile = multipartRequest.getFile("requestFile");
		File file = null;
		if (null != rcqFile) {
			if (!rcqFile.isEmpty()) {
				file = mapMultipartFileToFile(rcqFile);
			}
		}
		StructuredData strus = new StructuredData();
		Map<String, Object> map = strus.parseRequestData(file);
		url = (String) map.get("URL");
		method = (String) map.get("method");
		body = (String) map.get("body");
		Map<String, String> head = (Map<String, String>) map.get("headers");
		for (String k : head.keySet()) {
			if (k.equals("Authorization")) {
				key = k;
				value = head.get(k);
			} else {
				keyTwo = k;
				valueTwo = head.get(k);
			}
		}
		value = value.replaceAll("\"", "&quot;");
		request.setAttribute("url", url);
		request.setAttribute("body", body);
		request.setAttribute("key", key);
		request.setAttribute("value", value);
		request.setAttribute("method", method);
		if (null != valueTwo) {
			request.setAttribute("valueTwo", valueTwo);
		}
		if (null != keyTwo) {
			request.setAttribute("keyTwo", keyTwo);
		}
		return "restClient";
	}
}
